<template>
  <view class="asset-details">

    <!-- 资产信息 -->
    <view class="asset-info">
      <view class="asset-info-left">
        <view class="asset-name">{{ assetDetails?.assetName || '加载中...' }}</view>
        <view class="asset-id">编号: {{ assetDetails?.assetNumber || '加载中...' }}</view>
      </view>
      <view class="asset-info-right">
        <view class="asset-tag">{{ getAssetTypeText(assetDetails?.assetType) }}</view>
      </view>
    </view>

    <!-- 轮播图区域 -->
    <view class="carousel-section">
      <!-- 主轮播图 -->
      <swiper class="main-carousel" :current="currentIndex" @change="onSwiperChange"
        :indicator-dots="imageList.length > 1" :autoplay="false" :circular="imageList.length > 1">
        <swiper-item v-for="(item, index) in imageList" :key="index">
          <image :src="item.url" mode="aspectFill" class="main-image" @click="previewImage(index)"></image>
        </swiper-item>
      </swiper>

      <!-- 预览小图 -->
      <view class="thumbnail-section" v-if="imageList.length > 1">
        <scroll-view scroll-x class="thumbnail-scroll">
          <view class="thumbnail-list">
            <view v-for="(item, index) in imageList" :key="index" class="thumbnail-item"
              :class="{ active: currentIndex === index }" @click="switchToImage(index)">
              <image :src="item.url" mode="aspectFill" class="thumbnail-image"></image>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 更新资产信息按钮 -->
    <view class="update-button-section">
      <button class="update-button" @click="updateAssetInfo">
        更新资产信息
      </button>
    </view>

    <!-- 资产详细信息 -->
    <view class="asset-details-content">
      <uni-card :is-shadow="false" :border="false" margin="0" class="asset-card">
        <view class="detail-item">
          <text class="label">安全等级：</text>
          <text class="value">{{ getRankLevelText(assetDetails?.rankLv) }}</text>
        </view>
        <view class="detail-item">
          <text class="label">购入时间：</text>
          <text class="value">{{ formatDate(assetDetails?.purchaseTime) }}</text>
        </view>
        <view class="detail-item">
          <text class="label">购入价格：</text>
          <text class="value">{{ assetDetails?.purchasePrice || '暂无' }}</text>
        </view>
        <view class="detail-item">
          <text class="label">权属人：</text>
          <text class="value">{{ getOwnershipHolderName(assetDetails?.ownershipHolde) }}</text>
        </view>
        <view class="detail-item">
          <text class="label">证号：</text>
          <text class="value">{{ assetDetails?.propertyRightNum || '暂无' }}</text>
        </view>
        <view class="detail-item">
          <text class="label">地址：</text>
          <view class="address-container">
            <text class="value">{{ getCurrentAddress() }}</text>
            <uni-icons type="location" size="16" color="#666"></uni-icons>
          </view>
        </view>
        <view class="detail-item">
          <text class="label">面积：</text>
          <text class="value">{{ assetDetails?.area ? assetDetails.area + '㎡' : '暂无' }}</text>
        </view>
        <view class="detail-item">
          <text class="label">账面价值：</text>
          <text class="value">{{ assetDetails?.assetValuation || '暂无' }}</text>
        </view>
        <view class="detail-item">
          <text class="label">资产描述：</text>
          <text class="value">{{ assetDetails?.description || '暂无描述' }}</text>
        </view>
      </uni-card>
    </view>

    <!-- 记录标签页 -->
    <view class="records-section">
      <!-- 标签页导航 -->
      <uni-segmented-control :current="activeTab" :values="tabList" @clickItem="onTabChange" class="tab-control" />

      <!-- 记录内容区域 -->
      <view class="records-content">
        <!-- 抵押记录 -->
        <view v-if="activeTab === 0" class="record-list">
          <!-- 空状态 -->
          <view v-if="!mortgageRecords || mortgageRecords.length === 0" class="empty-container">
            <view class="empty-icon">📋</view>
            <text class="empty-text">暂无数据</text>
          </view>

          <!-- 列表 -->
          <uni-card v-else v-for="(item, index) in mortgageRecords" :key="index" :is-shadow="true" :border="false"
            margin="0" class="record-card">
            <view class="record-title">{{ item.financeTitle }}</view>
            <view class="record-details">
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">合同编号：</text>
                      <text class="value">{{ item.financeContractNumber }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">融资状态：</text>
                      <text class="value">{{ getFinanceStateText(item.financeState) }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">融资金额：</text>
                      <text class="value">{{ item.financeAmount }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">评估价值：</text>
                      <text class="value">{{ item.financeValuation }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">开始时间：</text>
                      <text class="value">{{ item.financeStartTime }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">结束时间：</text>
                      <text class="value">{{ item.financeEndTime }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">抵押人：</text>
                      <text class="value">{{ getOwnershipHolderName(item.mortgagor) }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">抵押权人：</text>
                      <text class="value">{{ item.mortgagee }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">抵押权人电话：</text>
                      <text class="value">{{ item.mortgageePhone }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
            </view>
          </uni-card>
          <!-- 分页器 -->
          <view class="pagination-container" v-if="mortgagePage.total > 0 && mortgageRecords.length > 0">
            <uni-pagination :total="mortgagePage.total" :pageSize="mortgagePage.pageSize"
              :current="mortgagePage.pageNum" @change="onMortgagePageChange" show-icon="true" />
          </view>
        </view>

        <!-- 租赁记录 -->
        <view v-if="activeTab === 1" class="record-list">
          <!-- 空状态 -->
          <view v-if="!leaseRecords || leaseRecords.length === 0" class="empty-container">
            <view class="empty-icon">📋</view>
            <text class="empty-text">暂无数据</text>
          </view>

          <!-- 列表 -->
          <uni-card v-else v-for="(item, index) in leaseRecords" :key="index" :is-shadow="true" :border="false"
            margin="0" class="record-card">
            <view class="record-title">{{ item.leaseName }}</view>
            <view class="record-details">
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">租赁编号：</text>
                      <text class="value">{{ item.contractNumber }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">缴纳状态：</text>
                      <text class="value">{{ getPaymentStatusText(item.paymentStatus) }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">租赁类型：</text>
                      <text class="value">{{ getLeaseTypeText(item.leaseType) }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">租金标准：</text>
                      <text class="value">{{ item.rentStandard }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">开始时间：</text>
                      <text class="value">{{ item.startTime }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">结束时间：</text>
                      <text class="value">{{ item.endTime }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">租赁业主：</text>
                      <text class="value">{{ getOwnershipHolderName(item.leaseOwner) }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">承租人：</text>
                      <text class="value">{{ item.tenant }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">承租人电话：</text>
                      <text class="value">{{ item.tenantPhone }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">备注：</text>
                      <text class="value">{{ item.notes }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
            </view>
          </uni-card>
          <!-- 分页器 -->
          <view class="pagination-container" v-if="leasePage.total > 0 && leaseRecords.length > 0">
            <uni-pagination :total="leasePage.total" :pageSize="leasePage.pageSize" :current="leasePage.pageNum"
              @change="onLeasePageChange" show-icon="true" />
          </view>
        </view>

        <!-- 生命周期 -->
        <view v-if="activeTab === 2" class="record-list">
          <!-- 空状态 -->
          <view v-if="!lifecycleRecords || lifecycleRecords.length === 0" class="empty-container">
            <view class="empty-icon">📋</view>
            <text class="empty-text">暂无数据</text>
          </view>

          <!-- 列表 -->
          <uni-card v-else v-for="(item, index) in lifecycleRecords" :key="index" :is-shadow="true" :border="false"
            margin="0" class="record-card">
            <view class="record-title">{{ item.assetName }}</view>
            <view class="record-details">
              <uni-row class="detail-row">
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">执行时间：</text>
                    <text class="value">{{ item.executionTime }}</text>
                  </view>
                </view>
              </uni-row>
              <uni-row class="detail-row">
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">执行人：</text>
                    <text class="value">{{ item.implementerName }}</text>
                  </view>
                </view>
              </uni-row>
            </view>
          </uni-card>
          <!-- 分页器 -->
          <view class="pagination-container" v-if="lifecyclePage.total > 0 && lifecycleRecords.length > 0">
            <uni-pagination :total="lifecyclePage.total" :pageSize="lifecyclePage.pageSize"
              :current="lifecyclePage.pageNum" @change="onLifecyclePageChange" show-icon="true" />
          </view>
        </view>

        <!-- 巡检记录 -->
        <view v-if="activeTab === 3" class="record-list">
          <!-- 空状态 -->
          <view v-if="!inspectionRecords || inspectionRecords.length === 0" class="empty-container">
            <view class="empty-icon">📋</view>
            <text class="empty-text">暂无数据</text>
          </view>

          <!-- 列表 -->
          <uni-card v-else v-for="(item, index) in inspectionRecords" :key="index" :is-shadow="true"
            :border="false" margin="0" class="record-card">
            <view class="record-title">
              <text>{{ item.assetName }}</text>
              <text class="detail-btn" @click="viewInspectionDetail(item)">详情</text>
            </view>
            <view class="record-details">
              <uni-row class="detail-row">
                <uni-col>
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">巡检时间：</text>
                      <text class="value">{{ item.patrolTime || '' }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
              <uni-row class="detail-row" :gutter="20">
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">巡检人员：</text>
                      <text class="value">{{ item.executor }}</text>
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="detail-col">
                    <view class="detail-item">
                      <text class="label">巡检结果：</text>
                      <text class="value">{{ item.inspectionResults }}</text>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
            </view>
          </uni-card>
          <!-- 分页器 -->
          <view class="pagination-container" v-if="inspectionPage.total > 0 && inspectionRecords.length > 0">
            <uni-pagination :total="inspectionPage.total" :pageSize="inspectionPage.pageSize"
              :current="inspectionPage.pageNum" @change="onInspectionPageChange" show-icon="true" />
          </view>
        </view>
      </view>
    </view>

    <!-- 巡检详情弹窗 -->
    <uni-popup ref="inspectionDetailPopup" type="center" @close="closeInspectionDetail">
      <view class="inspection-detail-popup">
        <uni-card v-if="currentInspectionItem" :is-shadow="true" :border="false" margin="0" class="record-card">
          <view class="popup-header">
            <text class="popup-title">巡检详情</text>
            <text class="close-icon" @click="closeInspectionDetail">×</text>
          </view>
          <view class="popup-content">
            <uni-row class="detail-row">
              <uni-col>
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">巡检时间：</text>
                    <text class="value">{{ currentInspectionItem.patrolTime || '' }}</text>
                  </view>
                </view>
              </uni-col>
            </uni-row>
            <uni-row class="detail-row">
              <uni-col>
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">巡检人员：</text>
                    <text class="value">{{ currentInspectionItem.executor }}</text>
                  </view>
                </view>
              </uni-col>
            </uni-row>
            <uni-row class="detail-row">
              <uni-col>
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">巡检结果：</text>
                    <text class="value">{{ currentInspectionItem.inspectionResults }}</text>
                  </view>
                </view>
              </uni-col>
            </uni-row>
            <uni-row class="detail-row">
              <uni-col>
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">备注：</text>
                    <text class="value">{{ currentInspectionItem.notes }}</text>
                  </view>
                </view>
              </uni-col>
            </uni-row>
            <uni-row class="detail-row">
              <uni-col>
                <view class="detail-col">
                  <view class="detail-item">
                    <text class="label">巡检照片：</text>
                    <text class="photo-list">
                      <template v-if="currentInspectionItem.picture">
                        <image v-for="(photo, index) in getPictureList(currentInspectionItem.picture)" :key="index" :src="baseUrl + photo"
                          class="photo-item" mode="aspectFill"></image>
                      </template>
                    </text>
                  </view>
                </view>
              </uni-col>
            </uni-row>
          </view>
        </uni-card>
      </view>
    </uni-popup>

    <!-- 更新资产信息弹窗 -->
    <uni-popup ref="updateAssetPopup" type="center" @close="closeUpdateAssetPopup">
      <view class="update-asset-popup">
        <view class="popup-header">
          <text class="popup-title">{{ assetDetails?.assetName || '资产详情' }}</text>
          <text class="close-icon" @click="closeUpdateAssetPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="location-section">
            <view class="location-info">
              <text class="location-label">位置：</text>
              <text class="location-value">{{ getCurrentAddress() }}</text>
            </view>
            <button class="update-location-btn" @click="updateLocation">更新位置</button>
          </view>
          <view class="album-section">
            <view class="album-title">资产相册：</view>
            <view class="album-content">
              <uni-file-picker v-model="assetPhotos" limit="9" title="最多选择9张大小不超过 5MB 的图片" file-mediatype="image"   @select="onPhotoSelect"
                @delete="onPhotoDelete"></uni-file-picker>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmUpdateAsset">确认</button>
          <button class="cancel-btn" @click="closeUpdateAssetPopup">取消</button>
        </view>
      </view>
    </uni-popup>

    <!-- 位置选择弹窗 -->
    <uni-popup ref="locationPopup" type="center" @close="cancelLocation">
      <view class="location-popup">
        <view class="popup-header">
          <text class="popup-title">位置选择</text>
          <text class="close-icon" @click="cancelLocation">×</text>
        </view>
        <view class="popup-content">
          <view class="search-section">
            <view class="search-input-container">
              <input v-model="searchKeyword" class="search-input" placeholder="搜索地点" type="text" @input="onInputTips" />
              <button class="search-btn">搜索</button>
            </view>
            <view class="tips-list" v-if="tips.length > 0">
              <view class="tip-item" v-for="(t, i) in tips" :key="i" @click="onSelectTip(t)">{{ t.name }}</view>
            </view>
          </view>
          <view class="location-input-section">
            <text class="input-label">位置信息：</text>
            <input v-model="locationInput" class="location-input" placeholder="点击地图选择位置" type="text" disabled />
          </view>
          <view class="map-section">
            <map class="map" 
              id="selectMap"
              :latitude="mapCenter.latitude" 
              :longitude="mapCenter.longitude" 
              :scale="mapScale"
              :markers="mapMarkers"
              show-location
              @tap="onMapTap"
              @click="onMapClick"
              @poitap="onPoiTap"
              @regionchange="onRegionChange">
            </map>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmLocation">确认</button>
          <button class="cancel-btn" @click="cancelLocation">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { getAsset, listFinance, listLease, listCycle, listRecord, updateAsset } from '@/api/asset.js'
import { getCompanyName } from '@/api/system/fund/fundUtil.js'
import useUserStore from '@/store/modules/user.js'
import { getToken } from '@/utils/auth'
// @ts-ignore
import amap from '@/libs/amap-wx.130.js'

// 基础URL
const baseUrl = import.meta.env.VITE_APP_BASE_URL

// 高德地图 Key（统一使用）
const AMAP_KEY = '918aa9ae565bc8f0a77d3bce0035dd86'
let myAmapFun: any = null

// 处理图片列表，将逗号分隔的字符串转换为数组
const getPictureList = (pictureStr: string) => {
  if (!pictureStr) return []
  return pictureStr.split(',').map(item => item.trim()).filter(item => item)
}

// 获取当前地址（优先显示表单中的地址，如果没有则显示资产详情中的地址）
const getCurrentAddress = () => {
  const currentAddress = form.value.address || assetDetails.value?.address || '暂无'
  console.log('当前地址:', currentAddress, '表单地址:', form.value.address, '资产详情地址:', assetDetails.value?.address)
  return currentAddress
}

// 转换图片路径为 uni-file-picker 需要的格式
const convertImageToFilePickerFormat = (imagePath: string) => {
  const fileName = imagePath.split('/').pop() || 'image.jpg'
  const extname = fileName.split('.').pop() || 'jpg'
  const result = {
    name: fileName,
    extname: extname,
    url: baseUrl + imagePath,
  }
  console.log('转换图片格式:', imagePath, '->', result)
  return result
}

// 资产详情数据
const assetDetails = ref<any>(null)
const currentAssetId = ref<string>('')

// 表单数据，用于存储修改后的资产信息
const form = ref<any>({})

// 获取资产详情
const fetchAssetDetails = async (assetId: string) => {
  try {
    const res = await getAsset(assetId)
    if (res.data) {
      assetDetails.value = res.data
      console.log('资产详情数据:', assetDetails.value)
      // 初始化表单数据
      form.value = { ...res.data }
      // 更新图片列表
      updateImageList(res.data)
    }
  } catch (error) {
    console.error('获取资产详情失败:', error)
    uni.showToast({
      title: '获取资产详情失败',
      icon: 'none'
    })
  }
}

// 抵押记录数据
const mortgageRecords = ref<any[]>([])
const mortgagePage = reactive({ pageNum: 1, pageSize: 2, total: 0 })

// 获取抵押记录
const fetchMortgageRecords = async (assetId: string) => {
  try {
    const userStore = useUserStore()
    if (!userStore.companyId) {
      await userStore.getInfo()
    }

    const queryParams = {
      pageNum: mortgagePage.pageNum,
      pageSize: mortgagePage.pageSize,
      assetId: assetId,
      financeTitle: null,
      financeContractNumber: null,
      financeState: null,
      mortgagee: null,
      mortgageePhone: null,
      createCompany: userStore.companyId
    }

    const res = await listFinance(queryParams)
    const rows = (res && res.rows) ? res.rows : []
    mortgageRecords.value = rows
    mortgagePage.total = res?.total ?? (Array.isArray(rows) ? rows.length : 0)
  } catch (error) {
    console.error('获取抵押记录失败:', error)
    mortgageRecords.value = []
  }
}

// 抵押分页切换：重新请求接口
const onMortgagePageChange = (e: any) => {
  mortgagePage.pageNum = e.current
  if (currentAssetId.value) {
    fetchMortgageRecords(currentAssetId.value)
  }
}

// 页面加载时获取资产详情
onMounted(() => {
  try {
    // 实例化 AMapWX
    // @ts-ignore
    myAmapFun = new amap.AMapWX({ key: AMAP_KEY })
  } catch (e) {
    console.warn('AMapWX 初始化失败:', e)
  }
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.options || {}
  const assetId = options.assetId

  if (assetId) {
    console.log('获取资产详情，ID:', assetId)
    currentAssetId.value = assetId
    fetchAssetDetails(assetId)
    fetchMortgageRecords(assetId)
    fetchLeaseRecords(assetId)
    fetchLifecycleRecords(assetId)
    fetchInspectionRecords()
  } else {
    console.error('未找到资产ID参数')
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    })
  }
})

// 融资状态文案
const getFinanceStateText = (state: any) => {
  const map: Record<string | number, string> = {
    0: '进行中',
    1: '已完成',
    2: '已终止'
  }
  const key = typeof state === 'string' ? state : Number(state)
  return map[key as any] ?? '未知'
}

// 缴纳状态文案
const getPaymentStatusText = (status: any) => {
  const map: Record<string | number, string> = {
    0: '未缴纳',
    1: '已缴纳'
  }
  const key = typeof status === 'string' ? status : Number(status)
  return map[key as any] ?? '未知'
}

// 租赁类型文案
const getLeaseTypeText = (type: any) => {
  const map: Record<string | number, string> = {
    0: '短期租赁',
    1: '长期租赁'
  }
  const key = typeof type === 'string' ? type : Number(type)
  return map[key as any] ?? '未知'
}

// 当前选中的图片索引
const currentIndex = ref(0)

// 图片列表数据
const imageList = ref([
  {
    url: '',
    title: '资产图片'
  }
])

// 更新图片列表
const updateImageList = (assetData: any) => {
  if (assetData && assetData.assetImage) {
    let imageArray: string[] = []
    
    // 检查 assetImage 是否为数组
    if (Array.isArray(assetData.assetImage)) {
      imageArray = assetData.assetImage
    } else {
      // 如果是字符串，按逗号分割
      imageArray = assetData.assetImage.split(',').map((item: string) => item.trim()).filter((item: string) => item)
    }
    
    // 处理图片数组
    if (imageArray.length > 0) {
      imageList.value = imageArray.map((image: string) => ({
        url: baseUrl + image,
        title: assetData.assetName || '资产图片'
      }))
      
      // 同步更新 assetPhotos，转换为 uni-file-picker 需要的格式
      assetPhotos.value = imageArray.map((image: string) => convertImageToFilePickerFormat(image))
    } else {
      // 如果没有有效图片，使用默认图片
      imageList.value = [{
        url: '/static/imgs/position.png',
        title: '资产图片'
      }]
      assetPhotos.value = []
    }
  } else {
    // 如果没有图片，使用默认图片
    imageList.value = [{
      url: '/static/imgs/position.png',
      title: '资产图片'
    }]
    assetPhotos.value = []
  }
  console.log(imageList.value);
  console.log('assetPhotos:', assetPhotos.value);
}

// 转换安全等级
const getRankLevelText = (rankLv: any) => {
  if (rankLv === null || rankLv === undefined || rankLv === '') {
    return '暂无'
  }

  const rankMap: { [key: number]: string } = {
    0: 'A',
    1: 'B',
    2: 'C',
    3: 'D'
  }

  return rankMap[rankLv] || '暂无'
}

// 转换资产类型
const getAssetTypeText = (assetType: any) => {
  if (assetType === null || assetType === undefined || assetType === '') {
    return '其他'
  }

  const typeMap: { [key: number]: string } = {
    0: '土地',
    1: '房产'
  }

  return typeMap[assetType] || '其他'
}

// 格式化日期
const formatDate = (dateString: any) => {
  if (!dateString) {
    return '暂无'
  }

  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) {
      return '暂无'
    }

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '暂无'
  }
}

// 获取权属人名称
const getOwnershipHolderName = (ownershipHolderId: any) => {
  if (!ownershipHolderId) {
    return '暂无'
  }

  try {
    const companyName = getCompanyName(ownershipHolderId)
    return companyName || '暂无'
  } catch (error) {
    console.error('获取权属人名称失败:', error)
    return '暂无'
  }
}

// 轮播图切换事件
const onSwiperChange = (e: any) => {
  currentIndex.value = e.detail.current
}

// 点击预览小图切换
const switchToImage = (index: number) => {
  currentIndex.value = index
}

// 预览图片
const previewImage = (index: number) => {
  const urls = imageList.value.map((item: any) => item.url)
  uni.previewImage({
    current: index,
    urls: urls
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 更新资产信息弹窗相关
const updateAssetPopup = ref<any>(null)

// 更新资产信息
const updateAssetInfo = () => {
  // 每次打开弹窗时，重新初始化表单数据为当前资产详情
  form.value = { ...assetDetails.value }
  // 同步更新 assetPhotos 为当前资产图片
  if (assetDetails.value && assetDetails.value.assetImage) {
    let imageArray: string[] = []
    if (Array.isArray(assetDetails.value.assetImage)) {
      imageArray = assetDetails.value.assetImage
    } else {
      imageArray = assetDetails.value.assetImage.split(',').map((item: string) => item.trim()).filter((item: string) => item)
    }
    
    if (imageArray.length > 0) {
      assetPhotos.value = imageArray.map((image: string) => convertImageToFilePickerFormat(image))
    } else {
      assetPhotos.value = []
    }
  } else {
    assetPhotos.value = []
  }
  
  updateAssetPopup.value.open()
}

// 关闭更新资产信息弹窗
const closeUpdateAssetPopup = () => {
  updateAssetPopup.value.close()
}

// 资产相册数据
const assetPhotos = ref<any[]>([])

// 位置选择弹窗相关
const locationPopup = ref<any>(null)
const locationInput = ref('')
const searchKeyword = ref('')
const tips = ref<any[]>([])

// 地图中心点
const mapCenter = ref({
  latitude: 30.871079,
  longitude: 105.388366
})

// 地图缩放级别
const mapScale = ref(14)

// 地图标记点
const mapMarkers = ref<any[]>([])

// 当前选中的位置
const selectedLocation = ref({
  latitude: 30.871079,
  longitude: 105.388366,
  address: ''
})

// 更新位置
const updateLocation = () => {
  // 初始化位置输入框为当前地址
  locationInput.value = getCurrentAddress()
  
  // 关闭第一个弹窗
  updateAssetPopup.value.close()
  // 显示位置选择弹窗
  setTimeout(() => {
    locationPopup.value.open()
  }, 100)
}

// 确认位置选择
const confirmLocation = () => {
  // 更新表单中的地址
  if (selectedLocation.value.address) {
    form.value.address = selectedLocation.value.address
    // 同时更新资产详情中的地址显示，确保界面立即更新
    assetDetails.value.address = selectedLocation.value.address
    console.log('位置已更新:', selectedLocation.value.address)
  }
  
  // 关闭位置选择弹窗
  locationPopup.value.close()
  // 重新显示第一个弹窗
  setTimeout(() => {
    updateAssetPopup.value.open()
  }, 100)
}

// 取消位置选择
const cancelLocation = () => {
  // 关闭位置选择弹窗
  locationPopup.value.close()
  // 重新显示第一个弹窗
  setTimeout(() => {
    updateAssetPopup.value.open()
  }, 100)
}


// 根据输入实时获取提示词（AMapWX.getInputtips）
const onInputTips = () => {
  if (!myAmapFun) return
  const keywords = searchKeyword.value.trim()
  if (!keywords) {
    tips.value = []
    return
  }
  try {
    myAmapFun.getInputtips({
      keywords,
      city: '射洪市',
      citylimit: true,
      location: `${mapCenter.value.longitude},${mapCenter.value.latitude}`,
      success: (data: any) => {
        if (data && data.tips) {
          tips.value = data.tips.filter((t: any) => !!t.name)
        } else {
          tips.value = []
        }
      },
      fail: () => {
        tips.value = []
      }
    })
  } catch (e) {
    tips.value = []
  }
}

// 选择提示词后定位到地图上
const onSelectTip = (tip: any) => {
  tips.value = []
  if (!tip) return
  const name = tip.name || ''
  const loc = tip.location || ''
  if (loc && loc.includes(',')) {
    const [lngStr, latStr] = loc.split(',')
    const longitude = parseFloat(lngStr)
    const latitude = parseFloat(latStr)
    if (!isNaN(latitude) && !isNaN(longitude)) {
      mapCenter.value = { latitude, longitude }
      placeMarkerAndResolve(latitude, longitude, name)
      selectedLocation.value.latitude = latitude
      selectedLocation.value.longitude = longitude
      selectedLocation.value.address = name
      locationInput.value = name
      return
    }
  }
  searchKeyword.value = name
}

// 提取事件中的坐标（兼容不同平台）
const extractLatLngFromEvent = (e: any): { latitude?: number; longitude?: number } => {
  if (e && e.detail) {
    // 小程序 map@tap 回调：e.detail = { latitude, longitude }
    if (typeof e.detail.latitude === 'number' && typeof e.detail.longitude === 'number') {
      return { latitude: e.detail.latitude, longitude: e.detail.longitude }
    }
    // H5 有些平台可能放在 e.detail.latlng 或者 e.detail.position
    // 做一些兼容性尝试
    const dl = (e.detail.latlng || e.detail.latLng || e.detail.position) as any
    if (dl && typeof dl.lat === 'number' && typeof dl.lng === 'number') {
      return { latitude: dl.lat, longitude: dl.lng }
    }
  }
  return { }
}

// 根据坐标放置图钉并尝试逆地理
const placeMarkerAndResolve = (latitude: number, longitude: number, presetAddress?: string) => {
  // 更新选中的位置
  selectedLocation.value = {
    latitude,
    longitude,
    address: presetAddress || ''
  }

  // 添加或更新标记点
  mapMarkers.value = [{
    id: 1,
    latitude,
    longitude,
    iconPath: '/static/imgs/position.png',
    width: 32,
    height: 32
  }]

  // 若有预设地址，直接显示
  if (presetAddress) {
    locationInput.value = presetAddress
    return
  }

  // 通过逆地理编码获取地址
  uni.request({
    url: `https://restapi.amap.com/v3/geocode/regeo`,
    method: 'GET',
    data: {
      key: AMAP_KEY,
      location: `${longitude},${latitude}`,
      extensions: 'all',
      radius: 1000,
      roadlevel: 0
    },
    success: (res: any) => {
      const data = res?.data || {}
      if (data.regeocode && data.regeocode.formatted_address) {
        const address = data.regeocode.formatted_address
        selectedLocation.value.address = address
        locationInput.value = address
      } else {
        // 回退：用周边搜索取最近的POI名称
        uni.request({
          url: `https://restapi.amap.com/v3/place/around`,
          method: 'GET',
          data: {
            key: AMAP_KEY,
            location: `${longitude},${latitude}`,
            radius: 1000,
            sortrule: 'distance'
          },
          success: (r2: any) => {
            const pois = r2?.data?.pois
            if (Array.isArray(pois) && pois.length > 0) {
              const name = pois[0].name || ''
              const addr = pois[0].address || ''
              const fallback = name || addr
              if (fallback) {
                selectedLocation.value.address = fallback
                locationInput.value = fallback
                return
              }
            }
            locationInput.value = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
          },
          fail: () => {
            locationInput.value = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
          }
        })
      }
    },
    fail: () => {
      locationInput.value = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
    }
  })
}

// 地图空白处点击（tap/click）
const onMapTap = (e: any) => {
  let { latitude, longitude } = extractLatLngFromEvent(e)
  // 部分平台 tap 无坐标，这里尝试使用 map 上下文转换屏幕坐标为经纬度（仅 H5/APP 支持）
  if (typeof latitude !== 'number' || typeof longitude !== 'number') {
    // @ts-ignore: uni.createMapContext 在不同端存在差异
    const ctx = uni.createMapContext && uni.createMapContext('selectMap')
    if (ctx && typeof ctx.getCenterLocation === 'function') {
      // 退化方案：取当前地图中心点作为点击位置
      ctx.getCenterLocation({
        success: (res: any) => {
          if (typeof res?.latitude === 'number' && typeof res?.longitude === 'number') {
            placeMarkerAndResolve(res.latitude, res.longitude)
          } else {
            uni.showToast({ title: '请点击兴趣点或使用搜索选择位置', icon: 'none' })
          }
        },
        fail: () => {
          uni.showToast({ title: '请点击兴趣点或使用搜索选择位置', icon: 'none' })
        }
      })
      return
    }
  }
  if (typeof latitude !== 'number' || typeof longitude !== 'number') {
    uni.showToast({ title: '请点击兴趣点或使用搜索选择位置', icon: 'none' })
    return
  }
  placeMarkerAndResolve(latitude, longitude)
}

// H5/APP 可能触发的 click 事件
const onMapClick = (e: any) => {
  const { latitude, longitude } = extractLatLngFromEvent(e)
  if (typeof latitude !== 'number' || typeof longitude !== 'number') return
  placeMarkerAndResolve(latitude, longitude)
}

// 地图视野变化（预留，必要时可用）
const onRegionChange = (_e: any) => {}

// 点击兴趣点（POI）
const onPoiTap = (e: any) => {
  // uni-app 下 e.detail 里包含 name/latitude/longitude
  const name = e?.detail?.name
  const latitude = e?.detail?.latitude
  const longitude = e?.detail?.longitude
  if (typeof latitude !== 'number' || typeof longitude !== 'number') return
  placeMarkerAndResolve(latitude, longitude, name)
}

// 选择照片
const onPhotoSelect = async (e: any) => {
  console.log('选择照片', e)
  
  if (!e.tempFiles || e.tempFiles.length === 0) {
    uni.showToast({
      title: '请选择图片',
      icon: 'none'
    })
    return
  }

  // 检查文件大小（5MB = 5 * 1024 * 1024 bytes）
  const maxSize = 5 * 1024 * 1024
  
  for (let i = 0; i < e.tempFiles.length; i++) {
    const file = e.tempFiles[i]
    
    if (file.size > maxSize) {
      uni.showToast({
        title: `图片 ${file.name} 超过5MB限制`,
        icon: 'none'
      })
      return
    }
  }

  // 上传所有选中的图片
  for (let i = 0; i < e.tempFiles.length; i++) {
    const file = e.tempFiles[i]
    await uploadImage(file)
  }
}

// 上传单张图片
const uploadImage = (file: any): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 检查token是否存在
    const token = getToken()
    if (!token) {
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      })
      reject(new Error('Token not found'))
      return
    }

    // @ts-ignore
    uni.showLoading({
      title: '上传中...'
    })

    // @ts-ignore
    uni.uploadFile({
      url: baseUrl + '/common/upload',
      filePath: file.path,
      name: 'file',
      header: {
        'Authorization': 'Bearer ' + getToken()
      },
      success: (uploadRes: any) => {
        // @ts-ignore
        uni.hideLoading()
        
        try {
          const result = JSON.parse(uploadRes.data)
          console.log('上传成功:', result)
          
          if (result.code === 200 && result.url) {
            // 将上传成功的图片添加到 assetPhotos
            const imagePath = result.url.replace(baseUrl, '')
            const newPhoto = convertImageToFilePickerFormat(imagePath)
            assetPhotos.value.push(newPhoto)
            
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: result.msg || '上传失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('解析上传响应失败:', error)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
        
        resolve()
      },
      fail: (error: any) => {
        // @ts-ignore
        uni.hideLoading()
        console.error('上传失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 删除照片
const onPhotoDelete = (e: any) => {
  console.log('删除照片', e)
  
  // e.index 是删除的图片索引
  if (e.index !== undefined && assetPhotos.value[e.index]) {
    const deletedPhoto = assetPhotos.value[e.index]
    console.log('删除的图片:', deletedPhoto)
    
    // 从 assetPhotos 中移除该图片
    assetPhotos.value.splice(e.index, 1)
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
  }
}

// 确认更新资产信息
const confirmUpdateAsset = async () => {
  try {
    // 将 assetPhotos 转换为 assetImage 格式
    let assetImage = ''
    if (assetPhotos.value && assetPhotos.value.length > 0) {
      const imageUrls = assetPhotos.value.map((photo: any) => {
        // 从完整URL中提取相对路径
        if (photo.url && photo.url.startsWith(baseUrl)) {
          return photo.url.replace(baseUrl, '')
        }
        return photo.url
      })
      assetImage = imageUrls.join(',')
    }
    
    // 更新表单数据
    form.value.assetImage = assetImage
    // 优先使用表单中的地址（可能已通过位置选择更新），如果没有则使用资产详情中的地址
    form.value.address = form.value.address || assetDetails.value.address
    
    console.log('更新资产信息参数:', form.value)
    
    const res = await updateAsset(form.value)
    
    if (res.code === 200) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
      // 重新获取资产详情
      if (currentAssetId.value) {
        await fetchAssetDetails(currentAssetId.value)
      }
      closeUpdateAssetPopup()
    } else {
      uni.showToast({
        title: res.msg || '更新失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('更新资产信息失败:', error)
    uni.showToast({
      title: '更新失败',
      icon: 'none'
    })
  }
}

// 巡检详情弹窗相关
const inspectionDetailPopup = ref<any>(null)
const currentInspectionItem = ref<any>(null)

// 查看巡检详情
const viewInspectionDetail = (item: any) => {
  console.log('点击详情按钮', item)
  currentInspectionItem.value = item
  inspectionDetailPopup.value.open()
}

// 关闭巡检详情弹窗
const closeInspectionDetail = () => {
  inspectionDetailPopup.value.close()
  currentInspectionItem.value = null
}

// 标签页相关
const activeTab = ref(0)
const tabList = ['抵押记录', '租赁记录', '生命周期', '巡检记录']

// 标签页切换
const onTabChange = (e: any) => {
  activeTab.value = e.currentIndex
}

// 抵押记录数据由接口获取，见 fetchMortgageRecords

// 租赁记录数据（服务端分页）
const leaseRecords = ref<any[]>([])
const leasePage = reactive({ pageNum: 1, pageSize: 2, total: 0 })

const fetchLeaseRecords = async (assetId: string) => {
  try {
    const userStore = useUserStore()
    if (!userStore.companyId) {
      await userStore.getInfo()
    }

    const queryParams = {
      pageNum: leasePage.pageNum,
      pageSize: leasePage.pageSize,
      assetId: assetId,
      leaseNumber: null,
      leaseName: null,
      leaseType: null,
      tenant: null,
      startTime: null,
      endTime: null,
      paymentStatus: null,
      createCompany: userStore.companyId
    }

    const res = await listLease(queryParams)
    const rows = (res && res.rows) ? res.rows : []
    leaseRecords.value = rows
    leasePage.total = res?.total ?? (Array.isArray(rows) ? rows.length : 0)
  } catch (error) {
    console.error('获取租赁记录失败:', error)
    leaseRecords.value = []
  }
}

const onLeasePageChange = (e: any) => {
  leasePage.pageNum = e.current
  if (currentAssetId.value) {
    fetchLeaseRecords(currentAssetId.value)
  }
}

// 生命周期数据（服务端分页）
const lifecycleRecords = ref<any[]>([])
const lifecyclePage = reactive({ pageNum: 1, pageSize: 4, total: 0 })

const fetchLifecycleRecords = async (assetId: string) => {
  try {
    const userStore = useUserStore()
    if (!userStore.companyId) {
      await userStore.getInfo()
    }

    const queryParams = {
      pageNum: lifecyclePage.pageNum,
      pageSize: lifecyclePage.pageSize,
      assetId: assetId,
      assetStatus: null,
      executionTime: null,
      createCompany: userStore.companyId
    }

    const res = await listCycle(queryParams)
    const rows = (res && res.rows) ? res.rows : []
    lifecycleRecords.value = rows
    lifecyclePage.total = res?.total ?? (Array.isArray(rows) ? rows.length : 0)
  } catch (error) {
    console.error('获取生命周期记录失败:', error)
    lifecycleRecords.value = []
  }
}

const onLifecyclePageChange = (e: any) => {
  lifecyclePage.pageNum = e.current
  if (currentAssetId.value) {
    fetchLifecycleRecords(currentAssetId.value)
  }
}

// 巡检记录数据（服务端分页）
const inspectionRecords = ref<any[]>([])
const inspectionPage = reactive({ pageNum: 1, pageSize: 4, total: 0 })

const fetchInspectionRecords = async () => {
  try {
    const userStore = useUserStore()
    if (!userStore.companyId) {
      await userStore.getInfo()
    }

    const queryParams = {
      pageNum: inspectionPage.pageNum,
      pageSize: inspectionPage.pageSize,
      patrolTime: null,
      executor: null,
      inspectionResults: null,
      createCompany: userStore.companyId
    }

    const res = await listRecord(queryParams)
    const rows = (res && res.rows) ? res.rows : []
    inspectionRecords.value = rows
    inspectionPage.total = res?.total ?? (Array.isArray(rows) ? rows.length : 0)
  } catch (error) {
    console.error('获取巡检记录失败:', error)
    inspectionRecords.value = []
  }
}

const onInspectionPageChange = (e: any) => {
  inspectionPage.pageNum = e.current
  fetchInspectionRecords()
}
</script>

<style lang="scss" scoped>
.asset-details {
  height: 100vh;
  background-color: #fff;
  overflow-y: auto;
  padding-bottom: 120rpx;
  -webkit-overflow-scrolling: touch;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  min-height: 200rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 15rpx;
}

.asset-info {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .asset-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .asset-id {
    font-size: 28rpx;
    color: #666;
  }

  .asset-info-right {
    width: 120rpx;

    .asset-tag {
      background: linear-gradient(135deg, #ffd700, #ffed4e);
      color: #333;
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      border: 1rpx solid #DCC53B;
      text-align: center;
      font-weight: bold;
    }

  }
}

.carousel-section {
  background-color: #fff;
  margin-bottom: 20rpx;

  .main-carousel {
    width: 100%;
    height: 500rpx;

    .main-image {
      width: 100%;
      height: 100%;
    }
  }

  .thumbnail-section {
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #eee;

    .thumbnail-scroll {
      width: 100%;
      white-space: nowrap;
    }

    .thumbnail-list {
      display: flex;
      gap: 20rpx;

      .thumbnail-item {
        flex-shrink: 0;
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
        overflow: hidden;
        border: 3rpx solid transparent;
        transition: all 0.3s ease;

        &.active {
          border-color: #007aff;
          transform: scale(1.05);
        }

        .thumbnail-image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}

.update-button-section {
  padding: 30rpx;
  display: flex;
  justify-content: center;

  .update-button {
    background: linear-gradient(135deg, #ff6b35, #ff8c42);
    border: none;
    border-radius: 20rpx;
    padding: 10rpx 50rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #fff;
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.3);
    width: 100%;
  }
}

.asset-details-content {
  padding: 0 30rpx;
  background-color: #fff;

  .asset-card {
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    overflow: hidden;
  }

  .description-card {
    border-radius: 16rpx;
    overflow: hidden;
  }

  .detail-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28rpx;
      color: #000;
      width: 160rpx;
      flex-shrink: 0;
    }

    .value {
      font-size: 28rpx;
      color: #666;
      flex: 1;
    }

    .address-container {
      display: flex;
      align-items: center;
      flex: 1;
      gap: 8rpx;
    }
  }

  .description-content {
    padding: 20rpx 0;

    .description-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}

.records-section {
  margin-top: 20rpx;
  background-color: #fff;

  .tab-control {
    margin: 30rpx;
    height: 60rpx;
  }

  .records-content {
    padding: 0 30rpx;
    margin-bottom: 30rpx;

    .record-list {
      .record-card {
        margin-bottom: 20rpx !important;
        border-radius: 16rpx;
        overflow: hidden;
        background-color: #fff;
        border: 1rpx solid #f0f0f0;

        .record-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          padding: 10rpx 0 0rpx 0;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .detail-btn {
            font-size: 24rpx;
            color: #007aff;
          }
        }

        .record-details {
          padding: 10rpx 0;

          .detail-item {
            padding: 12rpx 0;

            .label {
              font-size: 26rpx;
              color: #000;
            }

            .value {
              font-size: 26rpx;
              color: #666;
            }
          }
        }
      }
    }
  }

  // 租赁记录卡片样式
  .lease-card {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    border: 1rpx solid #f0f0f0;

    .lease-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }

    .lease-content {
      .lease-row {
        display: flex;
        gap: 40rpx;

        .lease-col {
          flex: 1;

          .lease-item {
            display: flex;
            align-items: center;
            padding: 12rpx 0;
            border-bottom: 1rpx solid #f5f5f5;

            &:last-child {
              border-bottom: none;
            }

            .lease-label {
              font-size: 28rpx;
              color: #666;
              width: 160rpx;
              flex-shrink: 0;
            }

            .lease-value {
              font-size: 28rpx;
              color: #333;
              flex: 1;
            }
          }
        }
      }
    }
  }
}

// 巡检详情弹窗样式
.inspection-detail-popup {
  background-color: #fff;
  border-radius: 16rpx;
  width: 90vw;
  max-height: 80vh;
  overflow: hidden;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .close-icon {
      font-size: 60rpx;
    }
  }

  .popup-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;

    .detail-item {
      padding: 20rpx 0;

      .label {
        font-size: 28rpx;
        color: #000;
        width: 160rpx;
        font-weight: bold;
      }

      .value {
        font-size: 28rpx;
        color: #666;
        line-height: 1.5;
      }

      .photo-list {
        display: flex;
        flex-wrap: wrap;

        .photo-item {
          width: 100rpx;
          height: 100rpx;
          margin: 10rpx;
        }
      }

    }
  }
}

// 更新资产信息弹窗样式
.update-asset-popup {
  background-color: #fff;
  border-radius: 16rpx;
  width: 90vw;
  max-height: 80vh;
  overflow: hidden;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 30rpx;
    border-bottom: 1rpx solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .close-icon {
      font-size: 50rpx;
      color: #666;
    }
  }

  .popup-content {
    padding: 30rpx;

    .location-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      .location-info {
        display: flex;
        align-items: center;

        .location-label {
          font-size: 28rpx;
          color: #333;
          font-weight: bold;
        }

        .location-value {
          font-size: 28rpx;
          color: #666;
          margin-left: 10rpx;
        }
      }

      .update-location-btn {
        background-color: #007aff;
        color: #fff;
        border: none;
        border-radius: 8rpx;
        padding: 10rpx 20rpx;
        font-size: 24rpx;
      }
    }

    .album-section {
      .album-title {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 20rpx;
      }

    }
  }

  .popup-footer {
    display: flex;
    padding: 30rpx;
    gap: 20rpx;
    border-top: 1rpx solid #eee;

    .confirm-btn,
    .cancel-btn {
      flex: 1;
      height: 80rpx;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;
      font-size: 28rpx;
      background-color: #fff;
      color: #333;
    }

    .confirm-btn {
      background-color: #007aff;
      color: #fff;
      border-color: #007aff;
    }
  }
}

// 位置选择弹窗样式
.location-popup {
  background-color: #fff;
  border-radius: 16rpx;
  width: 90vw;
  max-height: 80vh;
  overflow: hidden;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 30rpx;
    border-bottom: 1rpx solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .close-icon {
      font-size: 50rpx;
      color: #666;
    }
  }

  .popup-content {
    padding: 30rpx;

    .search-section {
      margin-bottom: 30rpx;

      .search-input-container {
        display: flex;
        gap: 20rpx;

        .search-input {
          flex: 1;
          height: 60rpx;
          border: 1rpx solid #ddd;
          border-radius: 8rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          background-color: #fff;
        }

        .search-btn {
          width: 120rpx;
          height: 60rpx;
          background-color: #007aff;
          color: #fff;
          border: none;
          border-radius: 8rpx;
          font-size: 28rpx;
        }
      }
    }

    .location-input-section {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;

      .input-label {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
        margin-right: 20rpx;
      }

      .location-input {
        flex: 1;
        height: 60rpx;
        border: 1rpx solid #ddd;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        background-color: #f8f8f8;
      }
    }

    .map-section {
      width: 100%;
      border-radius: 16rpx;
      overflow: hidden;

      .map {
        width: 100%;
        height: 500rpx;
      }
    }
  }

  .popup-footer {
    display: flex;
    padding: 30rpx;
    gap: 20rpx;

    .confirm-btn,
    .cancel-btn {
      flex: 1;
      height: 80rpx;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;
      font-size: 28rpx;
      background-color: #fff;
      color: #333;
    }

    .confirm-btn {
      background-color: #007aff;
      color: #fff;
      border-color: #007aff;
    }
  }
}
</style>
